<template>
  <section>
    <el-card class="margin-top">
      <div slot="header" class="clearfix relative">
        <el-row>
          <el-col
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            class="flex  align-center justify-start"
          >
            <span class="title-icon margin-right">箱单信息</span>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-download"
              @click="downPackingListInfo"
            >
              导出箱单信息
            </el-button>
            <el-button
              v-if="isEdit"
              type="primary"
              size="mini"
              icon="el-icon-upload2"
              @click="uploadDialog = true"
            >
              上传外箱标签文件
            </el-button>
          </el-col>
          <el-col
            :sm="23"
            :md="23"
            :lg="11"
            :xl="11"
            class="flex  align-center justify-between"
          >
            <div class="text-blue">
              <span class="margin-lr">总箱数：{{ totalAmount[0] }} </span>
              <span class="margin-lr">总数量：{{ totalAmount[1] }} </span>
              <span class="margin-lr">总重量：{{ totalAmount[2] }} </span>
            </div>
            <el-button
              v-if="isEdit"
              type="success"
              size="mini"
              @click="changeInfo"
            >
              确认箱单信息
            </el-button>
          </el-col>
          <el-col
            :sm="1"
            :md="1"
            :lg="1"
            :xl="1"
            class="text-right flex align-center"
            style="justify-content: flex-end;"
          >
            <i
              :class="{
                'el-icon-arrow-down': show,
                'el-icon-arrow-up': !show
              }"
              class="text-lg pointer margin-left"
              @click="show = !show"
            />
          </el-col>
        </el-row>
      </div>
      <div>
        <el-table
          v-show="show"
          ref="multipleTable"
          :header-cell-style="{ background: '#f5f9fc' }"
          size="mini"
          border
          :data="tableData"
          :span-method="objectSpanMethod"
          style="width: 100%;"
          class="margin-top "
          tooltip-effect="light"
        >
          <ex-table-column
            v-for="column in tableColumns"
            :key="column.prop"
            :auto-fit="true"
            :fit-header="true"
            :prop="column.prop"
            :label="column.label"
          >
            <template slot-scope="scope" class="column-wrapper">
              <template v-if="column.type === 'boolean'">
                {{
                  scope.row[column.prop] == 0
                    ? '否'
                    : scope.row[column.prop]
                    ? '是'
                    : ''
                }}
              </template>
              <template v-else>
                {{ scope.row[column.prop] }}
              </template>
            </template>
          </ex-table-column>
        </el-table>
      </div>
    </el-card>

    <ImportPop
      :upload-dialog.sync="uploadDialog"
      :dialog-title="`上传外箱标签文件`"
      :upload-tips="uploadTips"
      :action-url="`/abroad/waybills/uploadAbroadWaybillLabelFile`"
      :file-name="`uploadLabelFile`"
      :waybill-id="waybillId"
      @uploadCb="uploadCargoInfo"
    />
  </section>
</template>

<script>
import ImportPop from '@/components/ImportPop'

import { clone } from '@/utils/clone'
import 'handsontable/languages/zh-CN'
import globalData from '@/utils/config'
import {
  downloadAbroadPackList,
  saveAbroadPacking,
  updateAbroadConfirmFlag,
  deletePackingList
} from '@/api/abroadWaybill'
import { checkRowsEmpty } from '@/utils/waybill-public'
export default {
  name: 'PackingListInfo',
  components: {
    ImportPop
  },
  props: {
    packingList: {
      type: Array,
      default: function() {
        return [{}]
      }
    },
    actionUrl: {
      type: String,
      default: ''
    },
    returnCountry: {
      type: Number,
      default: 0
    },
    waybillId: [String, Number],
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      totalAmount: [0, 0, 0],
      uploadDialog: false,
      uploadTips: '',
      tipsList: [
        '一页6个标签',
        '一页1个标签，05中转仓一页6张标签或一页一张（plain paper）',
        '一页4个标签'
      ],
      waybillGoodsInfos: [{}, {}, {}, {}, {}],
      tableColumns: [
        {
          prop: 'cartonNo',
          label: '箱数'
        },
        {
          prop: 'oldSku', // 指定所指列
          label: '旧FNSKU'
        },
        {
          prop: 'sku',
          label: '新FNSKU'
        },
        {
          prop: 'num',
          label: '数量'
        },
        {
          prop: 'weight',
          label: '重量'
        },
        {
          prop: 'size',
          label: '外箱尺寸'
        }
      ],
      tableData: [],
      spanArr: [],
      pos: 0
    }
  },
  computed: {},
  watch: {
    returnCountry(nVal, oVal) {
      switch (nVal) {
        case 329:
        case 332:
        case 333:
          this.uploadTips = this.tipsList[0]
          break
        case 330:
          this.uploadTips = this.tipsList[1]
          break
        case 335:
        case 331:
        case 334:
        case 336:
          this.uploadTips = this.tipsList[2]
          break
      }
    },
    packingList(newValue, oldValue) {
      console.log('packingList :>> ', newValue)

      const arr = []
      for (const i of newValue) {
        console.log('i :>> ', i)
        if (i.abroadNewSkus) {
          for (const j of i.abroadNewSkus) {
            arr.push({
              id: i.id,
              cartonNo: i.cartonNo,
              waybillId: i.waybillId,
              size: i.size,
              weight: i.weight,
              sku: j.sku,
              oldSku: j.oldSku,
              skuId: j.id,
              num: j.num
            })
          }
        }
      }
      console.log('arr :>> ', arr)
      this.tableData = arr
      this.getSpanArr(this.tableData)
      this.total()
    }
  },

  methods: {
    // 计算表格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if ([0, 4, 5].includes(columnIndex)) {
        // 关键字段  shipmentId 一定要存在
        const target = this.packingList.find(x => x.cartonNo === row.cartonNo)
        // console.log('target.spanArr[rowIndex] :>> ', target.spanArr[rowIndex])
        const row_span =
          target && (this.spanArr[rowIndex] || this.spanArr[rowIndex] === 0)
            ? this.spanArr[rowIndex]
            : 1
        return {
          rowspan: row_span,
          colspan: 1
        }
      }
    },
    getSpanArr(arr) {
      // 数据排序，以便合并

      if (arr && arr.length > 0) {
        let spanArr = []
        let pos = 0

        arr.sort((a, b) => parseFloat(a.cartonNo) - parseFloat(b.cartonNo))
        spanArr = []
        pos = 0
        for (var i = 0; i < arr.length; i++) {
          if (i === 0) {
            spanArr.push(1)
            pos = 0
          } else {
            // 判断当前元素与上一个元素是否相同,因合并第一个所以[0]
            if (arr[i]['cartonNo'] === arr[i - 1]['cartonNo']) {
              spanArr[pos] += 1
              spanArr.push(0)
            } else {
              spanArr.push(1)
              pos = i
            }
          }
        }
        this.spanArr = spanArr
        // console.log('%cspanArr: ', 'color: #fff; background: #ccc;', spanArr)
        this.pos = pos
      }
    },
    total() {
      let boxs = 0
      let amounts = 0
      let weights = 0
      const arr = []
      for (const i of this.tableData) {
        if (i.cartonNo && !arr.includes(i.cartonNo)) {
          arr.push(i.cartonNo)
          if (i.weight) {
            weights += parseInt(i.weight)
          }
        }
        if (i.num && i.cartonNo) {
          amounts += Number(i.num)
        }
      }

      boxs = [...new Set(arr)].length
      this.totalAmount = [boxs, amounts, weights]
    },
    closeDialog() {
      this.uploadDialog = false
    },
    async downPackingListInfo() {
      this.$store.dispatch('app/toggleDialog', true)
      const { fileName } = await downloadAbroadPackList({
        id: this.waybillId
      })
      if (fileName) {
        window.open(globalData.fileUrl + fileName)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    uploadCargoInfo(file) {
      console.log('uploadCargoInfo', file)
    },
    changeInfo() {
      this.$confirm('确认该箱单信息么')
        .then(_ => {
          updateAbroadConfirmFlag({
            waybillId: this.waybillId
          }).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            } else {
              this.$message.error(res.message)
            }
          })

          // for (const i of this.$refs.hotTable.data) {
          //   if (
          //     !i.cartonNo ||
          //     !i.oldSku ||
          //     !i.sku ||
          //     !i.num ||
          //     !i.weight ||
          //     !i.size
          //   ) {
          //     this.$message.error('请填写必填信息')
          //     return
          //   }
          // }
          // this.saveInfo()
        })
        .catch(_ => {})
    },
    async saveInfo() {
      this.$store.dispatch('app/toggleDialog', true)

      const combined = this.packingList.reduce((acc, cur) => {
        const obj = {
          waybillId: this.waybillId,
          cartonNo: cur.cartonNo,
          size: cur.size,
          remark: cur.remark,
          abroadNewSkus: [],
          weight: cur.weight,
          id: cur.id
        }
        const newInfo = {
          oldSku: cur.oldSku,
          packListId: cur.id ? cur.id : '',
          sku: cur.sku,
          num: cur.num
        }
        obj.abroadNewSkus.push(newInfo)
        acc.push(obj)

        return acc
      }, [])
      console.log('combined', combined)

      // return;
      const { code, message } = await saveAbroadPacking({
        abroadPackingLists: combined
      })

      if (code === 200) {
        this.$message({
          type: 'success',
          message: '保存成功'
        })
      } else {
        this.$message.error(message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },
    coverRenderer(instance, td, row, col, prop, value, cellProperties) {
      td.innerHTML = `` // 清空单元格子集

      const btnDel = document.createElement('i')

      btnDel.setAttribute(
        'class',
        'el-icon-remove-outline margin-right-sm text-red pointer'
      )
      btnDel.setAttribute('v-loading.fullscreen.lock', 'fullscreenLoading')
      btnDel.onclick = params => {
        // console.log("this :>> ", this);
        this.onDel(row)
      }
      // if (
      //   (this.templateType === "receivable" && this.verifyShow.deleteRece) ||
      //   (this.templateType === "payable" && this.verifyShow.deletePay)
      // ) {
      td.appendChild(btnDel) // 添加按钮到单元格
      // }

      return td
    },
    // 删除
    async onDel(row) {
      console.log('row :>> ', row)
      this.loading = true
      if (this.packingList[row].id) {
        const data = await deletePackingList({
          id: this.packingList[row].id
        })
        if (data.code === 200) {
          this.$message.success('删除成功！')
          this.packingList.splice(row, 1)
        } else {
          this.$message.error(data.message || '删除失败！')
        }
      } else {
        this.packingList.splice(row, 1)
      }
      this.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.relative {
  .absolute {
    right: 10px;
    top: -40%;
  }
}
</style>
<style scoped>
/deep/ .el-card__header {
  padding: 8px 20px;
}
</style>
